package com.zhjhserver.main;
/*****************************************************************************************
 * 						诈金花游戏服务端
 * 1:使用Apache mina 框架
 * 2:集成了jdbc,驱动mysql数据库
 * 3:具体的数据库信息参见:MyDb.java的注释说明
 * ***************************************************************************************/
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.DefaultSocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.zhjhserver.database.MyDb;
import com.zhjhserver.socket.ActionScriptObjectFactory;
import com.zhjhserver.socket.ServerHandler;

public class ZhjhServer {
	private IoAcceptor ioAcceptor = null;
	private DefaultSocketSessionConfig sessionConfig = null;
	private Map<Long, IoSession> managedSessions = null;

	public ZhjhServer() throws IOException {
		this.ioAcceptor = new NioSocketAcceptor();
		this.sessionConfig = (DefaultSocketSessionConfig) ioAcceptor
				.getSessionConfig();
		this.sessionConfig.setReadBufferSize(1024 * 1024);
		this.sessionConfig.setReceiveBufferSize(1024 * 1024);
		this.sessionConfig.setTcpNoDelay(true);
		this.sessionConfig.setKeepAlive(true);
		//this.sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 10);
		this.ioAcceptor.getFilterChain().addLast(
				"flash",
				new ProtocolCodecFilter(new ActionScriptObjectFactory(Charset
						.forName("UTF-8"))));
		this.managedSessions = this.ioAcceptor.getManagedSessions();
		this.ioAcceptor.setHandler(new ServerHandler(this.managedSessions));
		this.ioAcceptor.bind(new InetSocketAddress(8888));
	}

	public static boolean startServer()
	{
		if (!MyDb.open())
		{
			return false;
		}

		try {
			new ZhjhServer();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public static void stopServer()
	{
		MyDb.close();
	}

	public static class ShutDownWork extends Thread {
		@Override
		public void run() {
			stopServer();
			System.out.println("Application end, 服务器关闭");
		}
	}

	public static void main(String[] args) {
		// 添加程序结束监听
        Runtime.getRuntime().addShutdownHook(new ShutDownWork());

        if (!startServer())
        {
        	System.exit(-1);
        }
	}
}

